<?php

namespace App\Service;

use App\Model\SensitiveModel;
use EasySwoole\ORM\Exception\Exception;
use Throwable;

class SensitiveService extends BaseService
{
    /**
     * @throws Exception
     * @throws Throwable
     */
    public function verify($param): array
    {
        $param = json_decode($param, true);
        $res = true;
        foreach ($param as $p) {
            $r = $this->checkKeyword($p);
            if ($r == false) {
                $res = false;
                break;
            }
        }

        if (!$res) {
            return [
                'result' => false,
                'msg' => '内容包含敏感词汇，请重新填写内容'
            ];
        }else{
            return [
                'result' => true
            ];
        }
    }

    /**
     * @param $keyword
     * @return bool
     * @throws Exception
     * @throws Throwable
     */
    public function checkKeyword($keyword): bool
    {
        $keywords = SensitiveModel::create()->all(['is_deleted' => 0]);
        if (empty($keywords)) {
            return true;
        }
        $check = true;
        foreach ($keywords as $v) {
            if (stristr(str_replace(' ', '', $keyword), $v['sensitive'])) {
                $check = false;
                break;
            }
        }
        return $check;
    }
}